import os
import time

import appium
from logger import logger
from selenium.webdriver import Keys
import keyboard
from appium import webdriver


class basePage:
    def __init__(self,driver):
        self.driver = driver

    #定位
    def find(self, *args):
        return self.driver.find_element(*args)

    def write(self, *args, text):
        self.find(*args).send_keys(text)

    def click(self, *args):
        self.find(*args).click()
    #滑动
    def swipe(self, x, y, x1, y1, du):
        # windowsize = self.driver.get_window_size()
        # heng = windowsize['width']
        # zong = windowsize['height']
        self.driver.swipe(
            start_x=x,
            start_y= y,
            end_x= x1,
            end_y= y1,
            duration=du
        )
    #清除
    def clean(self):
        try:
            self.find().clear()
        except:
            import keyboard
            logger.info("clean失败，尝试键盘操作")
            keyboard.press('backspace')
            keyboard.press('backspace')
            time.sleep(20)
            keyboard.release('backspace')
        # self.driver.clear()
    #关闭应用
    def close(self):
        import os
        os.system("adb shell am force-stop com.xingin.xhs")
    #安装应用
    def install(self,package_name):
        self.driver.install_app(package_name)
    #检测应用是否存在
    def is_app_installed(self,package_name):
        self.driver.is_app_installed(package_name)
    #删除应用
    def remove(self,package_name):
        self.driver.remove_app(package_name)
    #置于后台
    def background(self,time):
        self.driver.background_app(time)
    #高级手势轻敲
    # def tap(self, x, y):
    #     from appium.webdriver.common.touch_action import TouchAction
    #     touch_action = TouchAction(self.driver)
    #     windowsize = self.driver.get_window_size()
    #     heng = windowsize['width']
    #     zong = windowsize['height']
    #     touch_action.tap(x=x * heng, y=y * zong).perform()
    def tap(self,x,y):
        from appium.webdriver.common.touch_action import TouchAction
        touch_Action = TouchAction(self.driver)
        touch_Action.tap(x = x,y = y).perform()
    #高级手势按下
    def press(self,time):
        from appium.webdriver.common.touch_action import TouchAction
        touch_action = TouchAction(self.driver)
        touch_action.press(time).release().press()

    #jietu
    def screenshot(self, name_prefix):
        now = time.strftime("%Y-%m-%d %H_%M_%S")
        dirpath = './screenshot'
        os.makedirs(dirpath, exist_ok=True)
        reportName = dirpath + '/' + name_prefix + now + '.png'
        with open(reportName, 'wb') as f:
            self.driver.get_screenshot_as_png()

